﻿using ProjScan.Config;
using ProjScan.RecordManager;
using ProjScan.RecordManager.AssetData;
using ProjScan.ScanRule.Attr;
using ProjScan.Tools;
using UnityEngine;

namespace ProjScan.ScanRule.ArtAssets.Mesh
{
    [ArtAssetRuleAttr]
    internal class UVRangeTooLarge : RecordRuleImp<MeshRenderingAssetData, MeshRenderingRecordManager>
    {
        private float uvRangeMaxUVRange = 16f;

        protected override bool UseAssetDataCSVHeader => false;

        public UVRangeTooLarge()
        {
            ArtAssetsCheckConfig artAssetsCheckConfig = Singleton<ConfigMgr>.Instance.GetConfig<ArtAssetsCheckConfig>() as ArtAssetsCheckConfig;
            uvRangeMaxUVRange = artAssetsCheckConfig.uvRangeMaxUVRange;
        }

        protected override string GetDetailCSVHeader()
        {
            return "Name,DirID,UVRange";
        }

        public override void CheckDirSetted()
        {
            if (SeparateDirSettingsEnabled)
            {
                if (target_configs == null || target_configs.Length == 0)
                {
                    ScanLog.UnityLogError("美术资源检测规则 " + GetType().Name + " 执行失败，未设置目标文件夹");
                }

                if (target_configs.Length == 1 && target_configs[0].assetPath.StartsWith("Assets/ArtCheckFolder"))
                {
                    ScanLog.UnityLogError("美术资源检测规则 " + GetType().Name + " 执行失败，未设置目标文件夹");
                }
            }
        }

        public override bool CheckSupportability(out string msg)
        {
            msg = "";
            return true;
        }

        public static float CheckUVRange(UnityEngine.Mesh mesh)
        {
            Bounds bounds = new Bounds(Vector3.zero, Vector3.zero);
            Vector2[] uv = mesh.uv;
            foreach (Vector2 v in uv)
            {
                bounds.Encapsulate(v);
            }

            Vector2[] uv2 = mesh.uv2;
            foreach (Vector2 v2 in uv2)
            {
                bounds.Encapsulate(v2);
            }

            Vector2[] uv3 = mesh.uv3;
            foreach (Vector2 v3 in uv3)
            {
                bounds.Encapsulate(v3);
            }

            float a = Mathf.Abs(bounds.max.x - bounds.min.x);
            float b = Mathf.Abs(bounds.max.y - bounds.min.y);
            return Mathf.Max(a, b);
        }

        protected override bool IsOK(MeshRenderingAssetData assetData)
        {
            float num = CheckUVRange(assetData.asset);
            assetData.uvRange = num.ToString();
            return num <= uvRangeMaxUVRange;
        }
    }
}